# encoding=utf-8
# 获得淘宝cookie

import random
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains


class login_get_cookie(object):
    """
    电脑版
    登录获取cookie
    """

    def __init__(self, user_list, password_list):
        self.user_list = user_list
        self.password_list = password_list
        self.path = r'D:\工作第三方插件\淘宝滑动验证解决文件\第三方文件\chromedriver.exe'  # 本地文件地址路径

    def login(self, user, password):
        """登录"""
        option = Options()
        option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 指定为开发者模式规避 被检测到
        option.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2})  # 不加载图片 提快速度
        # option.add_argument(PROXPY_HOST)  # js注入方法 规避

        self.driver = webdriver.Chrome(executable_path=self.path, options=option)

        # self.driver.maximize_window()  # 最大化 页面

        self.driver.get('https://login.taobao.com/member/login.jhtml')
        time.sleep(2)

        try:
            self.driver.find_element_by_xpath('//a[@class="forget-pwd J_Quick2Static"]').click()  # 密码登录
            time.sleep(1)
        except Exception as e:
            pass

        user_element = self.driver.find_element_by_xpath('//input[@name="TPL_username"]')  # 用户名
        password_element = self.driver.find_element_by_xpath('//input[@name="TPL_password"]')  # 密码
        user_element.send_keys(user)
        time.sleep(1)
        password_element.send_keys(password)
        time.sleep(2)

        self.slid()  # 滑动

        login_url_ = self.driver.current_url
        if login_url_ == 'https://login.taobao.com/member/login.jhtml':
            password_element = self.driver.find_element_by_xpath('//input[@name="TPL_password"]')  # 密码
            time.sleep(1)
            password_element.send_keys(password)
            time.sleep(2)
            self.slid()

        login_url_list = self.driver.current_url
        login_url = login_url_list.split('?')[0]
        if login_url != 'https://i.taobao.com/my_taobao.htm' and login_url != 'https://www.taobao.com/':
            self.driver.quit()
            self.login(user, password)

        try:
            cookie_dict = self.driver.get_cookies()
        except Exception:
            self.driver.quit()
            cookie = self.login(user, password)
            return cookie

        self.driver.quit()

        cookie_dict_list = []  # cookie 处理过渡容器
        cookie_dict = {i["name"]: i["value"] for i in cookie_dict}
        for i in cookie_dict:
            s = "{}={};".format(i, cookie_dict[i])
            cookie_dict_list.append(s)

        cookie = (" ").join(cookie_dict_list)
        print(cookie)
        return cookie

    def slid(self):
        """滑动"""
        sl = self.driver.find_elements_by_xpath('//div[@id="nocaptcha" and @style="display: block;"]')
        if sl:
            time.sleep(3)
            sliding = self.driver.find_element_by_id("nc_1_n1z")  # 滑动验证
            ActionChains(self.driver).drag_and_drop_by_offset(sliding, 170, 0).drag_and_drop_by_offset(sliding, 100,
                                                                                                       0).perform()
            time.sleep(2)

            for i in range(3):
                refresh = self.driver.find_elements_by_xpath('//span[@class="nc-lang-cnt"]/a')
                if refresh:
                    refresh[0].click()
                    time.sleep(3)
                    sliding = self.driver.find_element_by_id("nc_1_n1z")  # 滑动验证
                    u = 200 + random.randint(0, 100)
                    ActionChains(self.driver).drag_and_drop_by_offset(sliding, u, 0).perform()
                    time.sleep(3)
                else:
                    break

        self.driver.find_element_by_id("J_SubmitStatic").click()  # 登录
        time.sleep(3)

    def save(self, user, cookie):
        """保存到Redis"""
        # 数据库操作

    def main(self):
        for user in self.user_list:
            password = self.password_list[self.user_list.index(user)]
            cookie = self.login(user, password)
            self.save(user, cookie)
            time.sleep(1)


# class login_get_cookie(object):
#     """
#     手机版本
#     登录获取cookie
#     """
#     def __init__(self, user_list, password_list):
#         self.user_list = user_list
#         self.password_list = password_list
#
#         self.path = r'D:\工作第三方插件\淘宝滑动验证解决文件\第三方文件\chromedriver.exe'  # 本地文件地址路径
#
#     def login(self, user, password):
#         """登录"""
#         option = Options()
#         option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 指定为开发者模式规避 被检测到
#         # option.add_argument(PROXPY_HOST)  # js注入方法 规避
#         option.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2})  # 不加载图片 提快速度
#
#         self.driver = webdriver.Chrome(executable_path=self.path, options=option)
#         self.driver.get('https://login.m.taobao.com/login.htm')
#
#         time.sleep(2)
#         try:
#             self.driver.find_element_by_xpath('//a[@class="forget-pwd J_Quick2Static"]').click()  # 密码登录
#             time.sleep(1)
#         except Exception as e:
#             pass
#
#         user_element = self.driver.find_element_by_xpath('//input[@name="TPL_username"]')  # 用户名
#         password_element = self.driver.find_element_by_xpath('//input[@name="TPL_password"]')  # 密码
#         user_element.send_keys(user)
#         password_element.send_keys(password)
#         time.sleep(2)
#
#         self.slid()  # 滑动
#
#         login_url_ = self.driver.current_url
#         if login_url_.split('?')[0] == 'https://login.m.taobao.com/login.htm':
#             password_element = self.driver.find_element_by_xpath('//input[@name="TPL_password"]')  # 密码
#             time.sleep(1)
#             password_element.send_keys(password)
#             time.sleep(2)
#             self.slid()
#
#         login_url_list = self.driver.current_url
#         login_url = login_url_list.split('?')[0]
#         if login_url != 'https://h5.m.taobao.com/mlapp/mytaobao.html' and login_url != 'https://www.taobao.com/':
#             self.driver.quit()
#             self.login(user, password)
#
#         try:
#             cookie_dict = self.driver.get_cookies()
#         except Exception:
#             self.driver.quit()
#             cookie = self.login(user, password)
#             return cookie
#
#         self.driver.quit()
#
#         cookie_dict_list = []  # cookie 处理过渡容器
#         cookie_dict = {i["name"]: i["value"] for i in cookie_dict}
#         for i in cookie_dict:
#             s = "{}={};".format(i, cookie_dict[i])
#             cookie_dict_list.append(s)
#
#         cookie = (" ").join(cookie_dict_list)
#         print(cookie)
#         return cookie
#
#     def slid(self):
#         """滑动"""
#         sl = self.driver.find_elements_by_xpath('//div[@class="sm-ico-wave"]')
#         if sl:
#             time.sleep(2)
#             sl[0].click()
#             time.sleep(7)
#
#         try:
#             # self.driver.switch_to.frame(0)  # 切换 iframe
#             shield = self.driver.find_element_by_xpath('//*[@id="nc_1_canvas"]')
#             shield.click()
#             time.sleep(0.5)
#             shield.click()
#             ActionChains(self.driver).click_and_hold().move_to_element_with_offset(shield, 5, 10).perform()
#             for i in range(7):
#                 time.sleep(random.randint(1, 2))
#                 ActionChains(self.driver).move_by_offset(random.randint(270, 280), 0).perform()
#                 time.sleep(random.randint(1, 2))
#                 ActionChains(self.driver).move_by_offset(-270, 18).perform()
#             time.sleep(1)
#             ActionChains(self.driver).move_to_element_with_offset(shield, random.randint(100, 200), random.randint(0, 20)).perform()
#             time.sleep(2)
#         except Exception as e:
#             # print(e)
#             pass
#
#         self.driver.find_element_by_xpath('//button[@class="am-button am-button-submit"]').click()  # 登录
#         time.sleep(3)
#
#         determines = self.driver.find_elements_by_xpath('//span[@class="km-dialog-btn"]')
#         if determines:
#             determines[0].click()
#
#     def access(self):
#         """访问店铺分类页面"""
#         self.driver.maximize_window()
#         self.driver.get(self.access_url)
#         time.sleep(2)
#
#         for i in range(4):
#             iframe = False  # 记录进入iframe
#             try:
#                 self.driver.switch_to.frame(1)  # 切换 iframe
#                 iframe = True
#             except Exception:
#                 pass
#
#             try:
#                 for i in range(7):
#                     slid_1 = self.driver.find_element_by_xpath('//span[@id="nc_1_n1z"]')  # 滑块
#                     # slid_1.click()
#                     for i in range(5):
#                         x = random.randint(50, 80)
#                         y = random.randint(50, 80)
#                         ActionChains(self.driver).move_by_offset(-x, -y).perform()  # 随机移动鼠标
#                         time.sleep(0.1)
#
#                     time.sleep(1)
#                     # ActionChains(self.driver).drag_and_drop_by_offset(slid_1, u, 0).perform()
#                     ActionChains(self.driver).click_and_hold(on_element=slid_1).perform()
#                     for i in range(56):
#                         ActionChains(self.driver).move_by_offset(5, 0).perform()
#                         time.sleep(0.003)
#                     time.sleep(3)
#                     sx = self.driver.find_elements_by_xpath('//span[@class="nc-lang-cnt"]/a')
#                     if sx:
#                         sx[0].click()
#                         time.sleep(3)
#                     else:
#                         break
#             except Exception as e:
#                 pass
#
#             if iframe:
#                 self.driver.switch_to.default_content()
#
#             self.driver.find_element_by_xpath('//div[@class="pager"]/ul/li[3]').click()  # 下一页按钮
#             time.sleep(2)
#
#     def save(self, user, password, cookie):
#         """保存到Redis"""
#         # 数据库操作
#
#     def main(self):
#         for user in self.user_list:
#             try:
#                 password = self.password_list[self.user_list.index(user)]
#                 cookie = self.login(user, password)
#                 self.save(user, password, cookie)
#             except Exception:
#                 self.driver.quit()


if __name__ == '__main__':
    users = ["13552070268"]
    passwords = ["quqingshuang000"]
    login_get_cookie(users, passwords).main()
